package com.malou.client.ventas.venta;

import java.util.ArrayList;
import java.util.List;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.filters.DateFilter;
import com.extjs.gxt.ui.client.widget.grid.filters.DateFilter.DateFilterMessages;
import com.extjs.gxt.ui.client.widget.grid.filters.GridFilters;
import com.extjs.gxt.ui.client.widget.grid.filters.NumericFilter;
import com.extjs.gxt.ui.client.widget.grid.filters.StringFilter;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.NumberFormat;
import com.malou.client.MalouConstants;
import com.malou.client.MalouMessages;
import com.malou.client.util.Utilities;

public class VentaPanel extends ContentPanel {
	
	private MalouConstants constants = GWT.create(MalouConstants.class);
	private MalouMessages messages = GWT.create(MalouMessages.class);
	private ToolBar toolBar;
	private Button nuevaVenta;
	private SeparatorToolItem separatorAnular;
	private Button anularVenta;
	public VentaDialog dialog;
	private List<BeanModel> selectedModels;
	private Integer selectedSize;
	private BeanModel selectedModel;
	
	public VentaPanel(){
		Ventas.getPaginate();
		Ventas.getDetalleVenta();
		final PagingToolBar toolBarPag = new PagingToolBar(Utilities.itemsPerPage);
		toolBarPag.bind(Ventas.loader);
		
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();		
		final CheckBoxSelectionModel<BeanModel> sm = new CheckBoxSelectionModel<BeanModel>();
		columns.add(sm.getColumn());
		
		ColumnConfig column = new ColumnConfig();
		columns.add(new ColumnConfig("documento", constants.ventaDocumento(), 80));
		columns.add(new ColumnConfig("numero", constants.ventaNumero(), 80));
		columns.add(new ColumnConfig("dni", constants.ventaDni(), 80));
		columns.add(new ColumnConfig("ruc", constants.ventaRuc(), 80));
		columns.add(new ColumnConfig("nombres", constants.ventaNombres(), 200));
		columns.add(new ColumnConfig("apellidos", constants.ventaApellidos(), 200));
		columns.add(new ColumnConfig("fecha", constants.ventaFecha(), 100));
		
		column = new ColumnConfig("total", constants.ventaTotal(), 100);
        column.setAlignment(HorizontalAlignment.RIGHT);
        column.setNumberFormat(NumberFormat.getFormat("0.00"));
        columns.add(column);        
		
		ColumnModel cm = new ColumnModel(columns);
		Grid<BeanModel> grid = new Grid<BeanModel>(Ventas.store, cm);  
        grid.addListener(Events.Attach, new Listener<GridEvent<BeanModel>>() {  
          public void handleEvent(GridEvent<BeanModel> be) {  
        	  Ventas.loader.load(0, Utilities.itemsPerPage);  
          }  
        });        
        
        grid.setLoadMask(true);  
        grid.setBorders(true);
        		
		setFrame(true);  
        setCollapsible(true);  
        setAnimCollapse(false);  
        
        setIcon(IconHelper.createPath("images/icons/table.png"));  
        setHeading(constants.ventaLista());  
        setLayout(new BorderLayout());
        
        toolBar = new ToolBar();
        
        nuevaVenta = new Button(constants.ventaNuevo(), IconHelper.createPath("images/icons/addstock.png"));
        
        dialog = new VentaDialog();
        SelectionListener<ButtonEvent> sl_new;       
        sl_new = new SelectionListener<ButtonEvent>(){
        	
        	@Override
			public void componentSelected(ButtonEvent ce) {	
				dialog.clearPrincipal();				
			    dialog.show();			    
			}
        };
        nuevaVenta.addSelectionListener(sl_new);
        toolBar.add(nuevaVenta);
        
        separatorAnular = new SeparatorToolItem();
		toolBar.add(separatorAnular);
		
		anularVenta = new Button(constants.ventaAnular(), IconHelper.createPath("images/icons/anular.png"));
		anularVenta.setEnabled(false);
		
		final Listener<MessageBoxEvent> l = new Listener<MessageBoxEvent>() {  
          public void handleEvent(MessageBoxEvent ce) {  
            String button_id = ce.getButtonClicked().getItemId();  
             if(Dialog.YES == button_id){
            	 Ventas.ventaDialog = dialog;
        		 
            	 if(selectedSize == 1){
            		 Integer id = selectedModel.get("id");            		 
            		 Ventas.anular(id);
            	 }else if(selectedSize > 1){
            		 List<Integer> ids = Utilities.toListIds(selectedModels);            		 
            		 Ventas.anularAll(ids);
            	 }
             }
          }  
        };
        
        SelectionListener<ButtonEvent> sl_anular;
        sl_anular = new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				String mensaje="";
				if(selectedSize == 1){
			
					String numero = selectedModel.get("numero");					
					mensaje = messages.ventaEstaSeguro(numero);				
				}else if(selectedSize > 1){
					mensaje = constants.anularAll();
				}
				MessageBox.confirm(constants.confirmacion(), mensaje, l).getDialog().getButtonById(Dialog.YES).setText(constants.si());
				
			}
			
		};
		
		anularVenta.addSelectionListener(sl_anular);
        toolBar.add(anularVenta);
        
        setTopComponent(toolBar);
        
        grid.setSelectionModel(sm);
        grid.getSelectionModel().addListener(Events.SelectionChange,
                new Listener<SelectionChangedEvent<BeanModel>>() {

				@Override
				public void handleEvent(SelectionChangedEvent<BeanModel> be) {		
					selectedSize = be.getSelection().size();
					if(selectedSize==0){						
						anularVenta.setEnabled(false);
						
						Ventas.storeDetalleVenta.removeAll();
					}else if(selectedSize==1){
						selectedModel = be.getSelectedItem();						
						anularVenta.setEnabled(true);
						
						Ventas.venta_id = selectedModel.get("id");
						Ventas.loaderDetalleVenta.load();
					}else if(selectedSize > 1){
						selectedModels = be.getSelection();						
						anularVenta.setEnabled(true);
						
						Ventas.storeDetalleVenta.removeAll();
					}					
				}
        	
        });
        
        GridFilters filters = new GridFilters();
        filters.getMessages().setFilterText(constants.filtros());
        
        StringFilter documentoFilter = new StringFilter("documento");
        StringFilter numeroFilter = new StringFilter("numero");
        StringFilter dniFilter = new StringFilter("dni");
        StringFilter rucFilter = new StringFilter("ruc");
        StringFilter nombresFilter = new StringFilter("nombres");
        StringFilter apellidosFilter = new StringFilter("apellidos");
        DateFilter fechaFilter = new DateFilter("fecha");
        
        DateFilterMessages dm= new DateFilterMessages();
        dm.setAfterText(constants.despues());
        dm.setBeforeText(constants.antes());
        dm.setOnText(constants.del());
        fechaFilter.setMessages(dm);
        
        
        NumericFilter totalFilter = new NumericFilter("total");
        
        filters.addFilter(documentoFilter);
        filters.addFilter(numeroFilter);
        filters.addFilter(dniFilter);
        filters.addFilter(rucFilter);
        filters.addFilter(nombresFilter);
        filters.addFilter(apellidosFilter);
        filters.addFilter(fechaFilter);
        filters.addFilter(totalFilter);
                
        grid.addPlugin(filters);        
        grid.addPlugin(sm);
        
        BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);  
        centerData.setMargins(new Margins(0));
        
        BorderLayoutData southData = new BorderLayoutData(LayoutRegion.SOUTH, 150);  
        southData.setSplit(true);        
        southData.setFloatable(true);  
        southData.setMargins(new Margins(5, 0, 0, 0));        
        ContentPanel maestro = new ContentPanel();
        maestro.setHeaderVisible(false);
        maestro.setLayout(new FitLayout());
        maestro.add(grid);
        maestro.setBottomComponent(toolBarPag);
        add(maestro, centerData);
        
 //     Detalle
        
        columns = new ArrayList<ColumnConfig>();
        column = new ColumnConfig();
		columns.add(new ColumnConfig("modeloprenda", constants.ventaModeloPrenda(), 300));
		
		column = new ColumnConfig("preciounitario", constants.ventaCosto(), 100);
        column.setAlignment(HorizontalAlignment.RIGHT);
        column.setNumberFormat(NumberFormat.getFormat("0.00"));
        columns.add(column);
        
        column = new ColumnConfig("cantidad", constants.ventaCantidad(), 80);
        column.setAlignment(HorizontalAlignment.RIGHT);        
        columns.add(column);
        
        column = new ColumnConfig("subtotal", constants.ventaSubtotal(), 80);
        column.setAlignment(HorizontalAlignment.RIGHT);
        column.setNumberFormat(NumberFormat.getFormat("0.00"));
        columns.add(column);
        
        cm = new ColumnModel(columns);
		
        Grid<BeanModel> detalle = new Grid<BeanModel>(Ventas.storeDetalleVenta, cm);        
        
        detalle.setLoadMask(true);  
        detalle.setBorders(true);		 
        
        add(detalle, southData);      
        
	}
	
	public void setPermisos(List<String> permisos){
		
		boolean add = permisos.contains("realizar");		
		boolean delete = permisos.contains("anular");
		
		if(!add && !delete){
			toolBar.setVisible(false);
		}else{
			if(!add){
				nuevaVenta.setVisible(false);
				separatorAnular.setVisible(false);
			}			
			if(!delete)
				anularVenta.setVisible(false);
		}
	}
}
